package com.nexgo.payment.trans;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.nexgo.oaf.apiv3.emv.PromptEnum;
import com.nexgo.payment.BaseTransPresenter;
import com.nexgo.payment.BaseTransView;
import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.action.confirmpan.ConfirmPanDialogFragment;
import com.nexgo.payment.action.inputamount.InputAmountFragment;
import com.nexgo.payment.action.inputpin.InputPinFragment;
import com.nexgo.payment.action.online.OnlineDialogFragment;
import com.nexgo.payment.action.readcard.ReadCardFragment;
import com.nexgo.payment.action.signature.SignatureFragment;
import com.nexgo.payment.action.transresp.TransRespFragment;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.fragment.EditDialogFragment;
import com.nexgo.payment.fragment.ProgressDialogFragment;
import com.nexgo.payment.fragment.TextDialogFragment;
import com.nexgo.payment.trans.download.DownloadTransActivity;
import com.nexgo.payment.trans.login.LoginActivity;
import com.nexgo.payment.trans.settle.SettleActivity;
import com.nexgo.payment.ui.BaseActivity;
import com.nexgo.payment.util.ActivityUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.sound.SoundManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import java8.util.Optional;

public abstract class AbsTransActivity<T extends BaseTransPresenter> extends BaseActivity implements OnActionListener, BaseTransView<T> {
    protected T mPresenter;
    private ProgressDialogFragment mWaitDialogFragment;
    private EditDialogFragment phoneDialogFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transaction);
    }

    @Override
    public void setWaitingIndicator(boolean active, String tipTitle, String tip) {
        if (active) {
            if (mWaitDialogFragment == null) {
                mWaitDialogFragment = new ProgressDialogFragment();
            }
            mWaitDialogFragment.setTip(tip);
            mWaitDialogFragment.setTipTitle(tipTitle);
            mWaitDialogFragment.setCancelable(false);
            mWaitDialogFragment.show(getSupportFragmentManager(), null);
        } else {
            if (mWaitDialogFragment != null) {
                mWaitDialogFragment.dismiss();
                mWaitDialogFragment = null;
            }
        }
    }

    @Override
    public void showUnsupported() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(R.string.unsupported), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onConfirm() {
                quitTrans();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showTransRecordLimit() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(R.string.trans_record_limit), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onConfirm() {
                intent2Activity(SettleActivity.class);
                quitTrans();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showLoginFirst() {
//        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
//        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
//        dialogFragment.setTitleText(getString(R.string.tip));
//        dialogFragment.setContentText(getString(R.string.login_first), Gravity.CENTER);
//        dialogFragment.setPositionText(getString(R.string.confirm));
//        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
//            @Override
//            public void onCancel() {
//
//            }
//
//            @Override
//            public void onConfirm() {
        Bundle bundle = new Bundle();
        bundle.putBoolean(LoginActivity.FORCE, true);
        intent2Activity(LoginActivity.class, bundle);
        quitTrans();
//            }
//        });
//        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showAdminCantTrade() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(R.string.admin_cant_trade), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onConfirm() {
                quitTrans();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showBatchUploadFirst() {
        TextDialogFragment textDialogFragment = new TextDialogFragment();
        textDialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_INFO);
        textDialogFragment.setTitleText(getString(R.string.kindly_tip));
        textDialogFragment.setContentText(getString(R.string.batch_upload_first), Gravity.CENTER);
        textDialogFragment.setPositionText(getString(R.string.confirm));
        textDialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onConfirm() {
                quitTrans();
            }
        });
        textDialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showError(String message) {
        SoundManager soundManager = new SoundManager();
        soundManager.play(SoundManager.Type.TRANS_FAIL);
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WRONG);
        dialogFragment.setTitleText(getString(R.string.tip));
        dialogFragment.setContentText(message, Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setDownTimer(SysConstant.TIME_OUT_10, true);
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onConfirm() {
                soundManager.stop();
                quitTrans();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showTransFailed() {
        showError(getString(R.string.trans_fail));
    }

    @Override
    public void showConnectFailed(){
        showError(getString(R.string.connect_fail));
    }

    @Override
    public void showInputAmount(TransData transData) {
        InputAmountFragment inputAmountFragment = InputAmountFragment.newInstance(transData);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.contentFrame);
        if (fragment == null) {
            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), inputAmountFragment, R.id.contentFrame);
        } else {
            ActivityUtils.replaceFragmentToActivity(getSupportFragmentManager(), inputAmountFragment, R.id.contentFrame);
        }
    }

    @Override
    public void showReadCard(TransData transData) {
        ReadCardFragment readCardFragment = ReadCardFragment.newInstance(transData);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.contentFrame);
        if (fragment == null) {
            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), readCardFragment, R.id.contentFrame);
        } else {
            ActivityUtils.replaceFragmentToActivity(getSupportFragmentManager(), readCardFragment, R.id.contentFrame);
        }
    }

    @Override
    public void showCardNoConfirm(TransData transData) {
        ConfirmPanDialogFragment confirmPanDialogFragment = ConfirmPanDialogFragment.newInstance(transData);
        confirmPanDialogFragment.setCancelable(false);
        confirmPanDialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showInputPin(TransData transData, boolean isOnlinePin, int leftTimes) {
        InputPinFragment inputPinFragment = InputPinFragment.newInstance(transData, isOnlinePin, leftTimes);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.contentFrame);
        if (fragment == null) {
            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), inputPinFragment, R.id.contentFrame);
        } else {
            ActivityUtils.replaceFragmentToActivity(getSupportFragmentManager(), inputPinFragment, R.id.contentFrame);
        }
    }

    @Override
    public void showSelApp(List<String> list) {
        SoundManager soundManager = new SoundManager();
        soundManager.play(SoundManager.Type.SELECT_APP);
        View dv = getLayoutInflater().inflate(R.layout.dialog_app_list, null);
        final AlertDialog alertDialog = new AlertDialog.Builder(this).setView(dv).create();
        ListView lv = (ListView) dv.findViewById(R.id.aidlistView);
        List<Map<String, String>> listItem = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = new HashMap<>();
            map.put("appIdx", (i + 1) + "");
            map.put("appName", list.get(i));
            listItem.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(this,
                listItem,
                R.layout.app_list_item,
                new String[]{"appIdx", "appName"},
                new int[]{R.id.tv_appIndex, R.id.tv_appName});
        lv.setAdapter(adapter);
        lv.setOnItemClickListener((parent, view, position, id) -> {
            Action<ActionStep> action = () -> ActionStep.SELECT_APP;
            alertDialog.dismiss();
            alertDialog.cancel();
            soundManager.stop();
            mPresenter.importActionResult(new ActionResult(action, ActionResult.SUCC, position + 1));
        });
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    @Override
    public void showConfirmEcSwitch() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(R.string.select_if_use_ec), Gravity.CENTER);
        dialogFragment.setNegativeText(getString(R.string.no));
        dialogFragment.setPositionText(getString(R.string.yes));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            Action<ActionStep> action = () -> ActionStep.CONFIRM_SWITCH_EC;

            @Override
            public void onCancel() {
                mPresenter.importActionResult(new ActionResult(action, ActionResult.SUCC, false));
            }

            @Override
            public void onConfirm() {
                mPresenter.importActionResult(new ActionResult(action, ActionResult.SUCC, true));
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showCertVerify(String certName, String certInfo) {

    }

    @Override
    public void showOnlineProc(TransData transData, String tip) {
        if(transData.getTransType()!=TransType.RISKTRADE){
            if(mPresenter.checkloctionIsNull()){
                startActivity(DownloadTransActivity.newInstance(this, TransType.RISKTRADE));
                finish();
                return;
            }
        }
        OnlineDialogFragment onlineDialogFragment = OnlineDialogFragment.newInstance(transData, tip);
        onlineDialogFragment.setCancelable(false);
        onlineDialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showElectronicSignature(String signature) {
        SignatureFragment signatureFragment = SignatureFragment.newInstance(signature);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.contentFrame);
        if (fragment == null) {
            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), signatureFragment, R.id.contentFrame);
        } else {
            ActivityUtils.replaceFragmentToActivity(getSupportFragmentManager(), signatureFragment, R.id.contentFrame);
        }
    }

    @Override
    public void showInputSignaturePhone() {
        phoneDialogFragment = new EditDialogFragment();
        phoneDialogFragment.setDialogType(EditDialogFragment.DIALOG_TYPE_INFO);
        phoneDialogFragment.addTitle(getString(R.string.please_input_phone_number));
        phoneDialogFragment.addEditText1(InputType.TYPE_CLASS_NUMBER, 11, null, false);
        phoneDialogFragment.setNegativeText(getString(R.string.cancel));
        phoneDialogFragment.setPositionText(getString(R.string.confirm));
        phoneDialogFragment.setDialogListener(new EditDialogFragment.OnDialogListener() {
            Action<ActionStep> action = () -> ActionStep.INPUT_PHONE;

            @Override
            public void onCancel() {
                mPresenter.importActionResult(new ActionResult(action, ActionResult.SUCC, null));
            }

            @Override
            public void onConfirm(List<String> values) {
                Iterator<String> iterator = values.iterator();
                mPresenter.importActionResult(new ActionResult(action, ActionResult.SUCC, iterator.next()));
            }
        });
        phoneDialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showDismissInputPhone() {
        if (phoneDialogFragment != null && phoneDialogFragment.getDialog() != null) {
            Dialog dialog = phoneDialogFragment.getDialog();
            if (dialog.isShowing()) {
                phoneDialogFragment.dismiss();
            }
            phoneDialogFragment = null;
        }
    }

    @Override
    public void showToast(String message) {
        Optional.ofNullable(message)
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> ToastUtils.showToast(s));
    }

    @Override
    public void showPrintReceipt() {
        System.out.println("---------去print----------");
        TransRespFragment transRespFragment = TransRespFragment.newInstance();
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.contentFrame);
        if (fragment == null) {
            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), transRespFragment, R.id.contentFrame);
        } else {
            ActivityUtils.replaceFragmentToActivity(getSupportFragmentManager(), transRespFragment, R.id.contentFrame);
        }
    }

    @Override
    public void setActionResult(ActionResult result) {
        System.out.println("---------返回结果的一个动作-----将要进入AbsTransPresenter------");
        mPresenter.importActionResult(result);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.destroy();
        }
    }

    @Override
    public void quitTrans() {
        finish();
    }

    @Override
    public void setPresenter(T presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showEmvPrompt(PromptEnum prompt) {
        String tip = "";
        switch (prompt) {
            case APP_SELECTION_IS_NOT_ACCEPTED:
                tip = getString(R.string.not_accept_please_try_again);
                break;
            case OFFLINE_PIN_INCORRECT_TRY_AGAIN:
                tip = getString(R.string.offline_pin_incorrect_try_again);
                break;
            case OFFLINE_PIN_INCORRECT:
                tip = getString(R.string.offline_pin_incorrect);
                break;
            case OFFLINE_PIN_CORRECT:
                tip = getString(R.string.offline_pin_correct);
                break;
            default:
                break;
        }
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(tip, Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.yes));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            Action<ActionStep> action = () -> ActionStep.EMV_PROMPT;

            @Override
            public void onCancel() {
                mPresenter.importActionResult(new ActionResult(action, ActionResult.SUCC, false));
            }

            @Override
            public void onConfirm() {
                mPresenter.importActionResult(new ActionResult(action, ActionResult.SUCC, true));
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }
}
